/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/binary-tree-postorder-traversal
   @Language: C++
   @Datetime: 16-02-09 04:45
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

// Method 1, recursion, Time 50ms
class Solution {
	/**
	 * @param root: The root of binary tree.
	 * @return: Postorder in vector which contains node values.
	 */
	void postorder(TreeNode *r, vector<int> &vs){
		if (r==NULL) return;
		postorder(r->left,vs);
		postorder(r->right,vs);
		vs.push_back(r->val);
	}
public:
	vector<int> postorderTraversal(TreeNode *root) {
		// write your code here
		vector<int> vs;
		postorder(root,vs);
		return vs;
	}
};

// Method 2, loop, Time 50ms
class Solution {
	/**
	 * @param root: The root of binary tree.
	 * @return: Postorder in vector which contains node values.
	 */
public:
	vector<int> postorderTraversal(TreeNode *root) {
		// write your code here
		vector<int> v;
		if(root==NULL) return v;
		stack<TreeNode*> s;
		for(s.push(root); s.size();){
			root=s.top();
			s.pop();
			if(root->left) s.push(root->left);
			if(root->right) s.push(root->right);
			v.push_back(root->val);
		}
		reverse(v.begin(),v.end());
		return v;
	}
};
